<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-specification-breakdown">
    <view class="spec-data">
      <view class="spec-item">
        <view class="status">
          <view class="sku-data">
            <view
              v-for="(itemN, indexN) in specList"
              :key="indexN"
              class="sku-item line"
            >
              <view
                class="sku-name"
                @tap="changeCollapse(indexN, !(specTeamSel == indexN))"
              >
                <view class="sku-name-con">
                  {{ itemN.name }}
                </view>
                <uni-icons
                  :type="specTeamSel == indexN ? 'top' : 'bottom'"
                  class="sku-name-icon"
                />
              </view>
              <view
                class="sku-list"
                :style="{ 'display': specTeamSel == indexN ? 'block' : 'none' }"
              >
                <view
                  :class="['sku-list-item', collSelect[indexN] === '' ? 'spec-active' : '']"
                  @tap="clickSkuName('', indexN)"
                >
                  全部规格
                </view>
                <view
                  v-for="(itemV, indexV) in itemN.prodPropValues"
                  :key="indexV"
                  :class="['sku-list-item', collSelect[indexN] === itemV.name ? 'spec-active' : '']"
                  @tap="clickSkuName(itemV.name, indexN)"
                >
                  {{ itemV.name }}
                </view>
              </view>
            </view>
          </view>
        </view>
        <view
          v-show="isMask"
          class="mask"
          @click="closeVal"
        />
      </view>
    </view>
    <!--input列表 -->
    <view class="box">
      <view
        v-for="(item, index) in dataForm"
        :key="index"
        class="input-box"
      >
        <view v-show="item.isShow">
          <view class="label-data-box">
            <view class="label-data">
              <radio
                v-if="isbatch"
                class="item-radio"
                :checked="item.isSelect"
                color="#082ba6"
                @tap="clickSpec(index)"
              />
              <view
                v-for="(specItem, specIndex) in item.name"
                :key="specIndex"
                class="data-item"
              >
                <view class="data-name">
                  {{ specItem }}
                </view>
              </view>
            </view>
            <!-- <switch :checked="item.status" @change="changeStatus(index)" /> -->
            <text
              :class="['sku-status', 'sku-status1']"
              @tap.stop="changeStatus(index)"
            >
              {{ item.status ? '禁用' : '启用' }}
            </text>
          </view>

          <view class="section">
            <text>销售价(元)<span class="red">*</span></text>
            <input
              v-if="item.status"
              v-model="item.price"
              placeholder="请填写"
              type="digit"
              maxlength="15"
              @blur="changeNum(index, 'price')"
            >
            <view
              v-else
              class="disabled-text"
            >
              {{ item.price }}
            </view>
          </view>
          <view class="section">
            <text>库存<span class="red">*</span></text>
            <input
              v-if="item.status"
              v-model="item.stocks"
              placeholder="请填写"
              type="number"
              maxlength="15"
              @blur="changeInventory(index)"
            >
            <view
              v-else
              class="disabled-text"
            >
              {{ item.stocks }}
            </view>
          </view>
          <view class="section">
            <text>市场价(元)</text>
            <input
              v-if="item.status"
              v-model="item.oriPrice"
              placeholder="划线价(选填)"
              type="digit"
              maxlength="15"
              @blur="changeNum(index, 'oriPrice')"
            >
            <view
              v-else
              class="disabled-text"
            >
              {{ item.oriPrice }}
            </view>
          </view>
          <view
            v-if="prodStore.mold !== 1"
            class="section"
          >
            <text>商品体积(m³)</text>
            <input
              v-if="item.status"
              v-model="item.volume"
              placeholder="请填写(选填)"
              type="digit"
              maxlength="15"
              @blur="changeNum(index, 'volume')"
            >
            <view
              v-else
              class="disabled-text"
            >
              {{ item.volume }}
            </view>
          </view>
          <view
            v-if="prodStore.dataForm.mold !== 1"
            class="section"
          >
            <text>商品重量(kg)</text>
            <input
              v-if="item.status"
              v-model="item.weight"
              placeholder="请填写(选填)"
              type="digit"
              maxlength="15"
              @blur="changeNum(index, 'weight')"
            >
            <view
              v-else
              class="disabled-text"
            >
              {{ item.weight }}
            </view>
          </view>
          <view class="section">
            <text>商品编码</text>
            <input
              v-if="item.status"
              v-model="item.partyCode"
              placeholder="如无编码将自动生成"
              type="text"
              maxlength="30"
              @blur="changeCode(index)"
            >
            <view
              v-else
              class="disabled-text"
            >
              {{ item.partyCode || '如无编码将自动生成' }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- end input列表 -->

    <!-- 功能按钮 -->
    <common-btn
      v-if="!isbatch"
      :btn-config="prodManaBtnConfig1"
      class="common-btn"
      @handle-click-more-btn="MoreBtnOne"
    />
    <common-btn
      v-else
      :btn-config="prodManaBtnConfig2"
      class="common-btn"
      @select-all-btn="selectAllBtn"
      @handle-click-more-btn="MoreBtnTwo"
    />
    <!-- end 功能按钮 -->

    <!-- 批量设置规格值 -->
    <batch-specification
      v-if="isSetting"
      :mlod="prodStore.dataForm.mold"
      @cancal="closeBatch"
      @handle-click-btn="handleClickBtn"
    />
  </view>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import BatchSpecification from '../../components/batch-specification/batch-specification.vue'

const prodStore = useProdStore()

const Data = reactive({
  dataForm: [], // 明细数据
  collSelect: [], // 规格值筛选值
  specTeamSel: -1, // 展开下拉框index

  isbatch: false, // 是否批量选择
  isSetting: false, // 批量设置显示
  selectSpecList: [], // 批量设置选中数据列表
  isMask: false, // 遮罩层
  specList: [], // 规格数据

  // 按钮tip
  prodManaBtnConfig1: {
    isPlain: true,
    btnList: [
      {
        btnText: '批量操作',
        isPlain: false
      },
      {
        btnText: '确定',
        isPlain: false
      }
    ]
  },
  prodManaBtnConfig2: {
    isPlain: true,
    isChecked: false,
    isSelect: true,
    btnList: [
      {
        btnText: '退出批量',
        isPlain: false
      },
      {
        btnText: '批量设置',
        isPlain: false
      }
    ]
  }
})

const { dataForm, collSelect, specTeamSel, isbatch, isSetting, isMask, specList, prodManaBtnConfig1, prodManaBtnConfig2 } = toRefs(Data)

onMounted(() => {
  // 页面滚到顶部
  nextTick(() => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 1
    })
  })

  const specData = prodStore.dataForm.skuList
  dealSpecData(specData)
})

onShow(() => {
  // 加载导航标题
  uni.setNavigationBarTitle({
    title: '规格明细'
  })
})

// 处理显示数据
const dealSpecData = (data) => {
  if (data.length > 0) {
    const valueObj = {}
    const nameList = data[0].properties.split(';').map((item) => {
      const name = item.slice(0, item.indexOf(':'))
      valueObj[name] = []
      return name
    })
    const skuList = []
    data.forEach((item) => {
      item.isSelect = false
      item.changeStock = parseInt(item.stocks)
      item.name = item.properties.split(';').map((item) => {
        return item.substring(item.indexOf(':') + 1)
      })
      item.isShow = true

      const list = item.properties.split(';')
      for (let i = 0; i < nameList.length; i++) {
        const index = list[i].indexOf(':')
        const sku = [list[i].slice(0, index), list[i].substring(index + 1)]
        if (skuList.indexOf(sku[0] + '-' + sku[1]) < 0) {
          skuList.push(sku[0] + '-' + sku[1])
          valueObj[sku[0]].push({
            isSelect: true,
            name: sku[1],
            pic: (i === 0 ? item.pic : ''),
            propId: item.prodId,
            propValue: sku[1],
            propValueEn: sku[1],
            valueId: ''
          })
        }
      }
    })
    Data.dataForm = data
    nameList.forEach((item) => {
      Data.specList.push({
        name: item,
        prodPropValues: valueObj[item]
      })
    })
    Data.collSelect = new Array(...Data.specList.map(() => {
      return ''
    }))
  }
}

// 提交
const submitBtn = () => {
  let isNullLen = 0
  Data.dataForm.forEach((item) => {
    item.changeStock = item.stocks - item.changeStock
    if (item.stocks === 0) {
      isNullLen++
    }
  })
  if (isNullLen === Data.dataForm.length) {
    uni.showModal({
      content: '该商品库存为0，确认保存？',
      icon: 'none',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          prodStore.dataForm.skuList = Data.dataForm
          uni.navigateTo({
            url: '/package-prod/pages/post-prod/post-prod'
          })
        }
      }
    })
  } else {
    prodStore.dataForm.skuList = Data.dataForm
    uni.navigateTo({
      url: '/package-prod/pages/post-prod/post-prod'
    })
  }
}

const { proxy } = getCurrentInstance()
// 选择批量操作规格
const clickSpec = (index) => {
  Data.dataForm[index].isSelect = !Data.dataForm[index].isSelect
  const allData = Data.dataForm.filter((item) => item.isShow)
  if (Data.dataForm[index].isSelect) {
    Data.selectSpecList.push(index)
  } else {
    Data.selectSpecList.splice(Data.selectSpecList.indexOf(index), 1)
  }
  if (Data.selectSpecList.length === allData.length) {
    Data.prodManaBtnConfig2.isChecked = true
  } else {
    Data.prodManaBtnConfig2.isChecked = false
  }
  proxy.$forceUpdate()
}

const changeStatus = (index) => {
  const obj = Data.dataForm[index]
  obj.status = obj.status ? 0 : 1
  Data.dataForm[index] = obj
}

// 点击按钮组件回调（批量，确定）
const MoreBtnOne = (index) => {
  switch (index) {
    case 1:
      batchEdit()
      break
    case 2:
      submitBtn()
  }
}

// 点击按钮组件回调2（退出批量，批量）
const MoreBtnTwo = (index) => {
  switch (index) {
    case 1:
      escBatch()
      break
    case 2:
      batchSubmit()
  }
}

// 库存校验
const changeInventory = (index) => {
  let num = Data.dataForm[index].stocks
  num = Number(num).toFixed(0)
  num = Number(num.toString().replace(/[^\d]/g, ''))
  if (num > 9999999) {
    num = 9999999
  }
  Data.dataForm[index].stocks = Number(num)
}

// 输入金额校验
const changeNum = (index, type) => {
  const obj = Data.dataForm[index]
  obj[type] = checkInput(obj[type])
  if (!obj[type] && type !== 'price') {
    obj[type] = 0
  } else if (!obj[type]) {
    obj[type] = 0.01
  }

  if ((type === 'price' || type === 'oriPrice') && obj[type] > 10000000) {
    obj[type] = 10000000
  }
  Data.dataForm[index] = obj
}

// 校验商品编码
const changeCode = (index) => {
  const obj = Data.dataForm[index]
  if (obj.partyCode === '') return
  const codeList = Data.dataForm.map(x => {
    return x.partyCode
  }).sort()
  const num = codeList.lastIndexOf(obj.partyCode) - codeList.indexOf(obj.partyCode) + 1
  if (num > 1) {
    uni.showToast({
      title: '商品编码不能重复',
      mask: true,
      icon: 'none',
      duration: 1000
    })
    obj.partyCode = ''
    Data.dataForm[index] = obj
  }
}

/**
     * input输入框只允许输入正数和小数(保留小数点后两位)
     */
const checkInput = (num) => {
  if (num) {
    num = num < 0.01 ? 0.01 : num
    let tmpVal = parseFloat(num.toString().replace(/[^\d^\\.]/g, ''))
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

// 批量操作
const batchEdit = () => {
  Data.isbatch = true
}

// 退出批量
const escBatch = () => {
  Data.isbatch = false
  selectAllBtn(false)
}

// 批量设置
const batchSubmit = () => {
  if (Data.selectSpecList.length > 0) {
    Data.isSetting = true
  } else {
    uni.showToast({
      title: '请选择设置属性',
      mask: true,
      icon: 'none',
      duration: 1000
    })
  }
}

// 退出批量设置
const closeBatch = () => {
  Data.isSetting = false
}

// 批量设置提交
const handleClickBtn = (obj) => {
  Data.isSetting = false
  Data.dataForm.forEach((item, index) => {
    if (Data.selectSpecList.indexOf(index) >= 0 && item.status === 1) {
      item.price = (obj.price ? obj.price : item.price)
      item.stocks = (obj.stocks ? obj.stocks : item.stocks)
      item.oriPrice = (obj.oriPrice ? obj.oriPrice : item.oriPrice)
      item.volume = (obj.volume ? obj.volume : item.volume)
      item.weight = (obj.weight ? obj.weight : item.weight)
    }
  })
}

// 全选事件
const selectAllBtn = (val) => {
  Data.selectSpecList = []
  if (val) {
    Data.dataForm.forEach((item, index) => {
      if (item.isShow) {
        Data.selectSpecList.push(index)
      }
    })
    Data.selectSpecList.forEach((item) => {
      Data.dataForm[item].isSelect = true
    })
    Data.prodManaBtnConfig2.isChecked = true
  } else {
    Data.dataForm.forEach((item) => {
      item.isSelect = false
    })
    Data.prodManaBtnConfig2.isChecked = false
  }
  proxy.$forceUpdate()
}

// 筛选规格值显示
const clickSkuName = (name, index) => {
  const newList = JSON.parse(JSON.stringify(Data.collSelect))
  Data.collSelect[index] = name
  if (newList.toString() === Data.collSelect.toString()) return
  selectAllBtn(false)
  Data.selectSpecList = []
  const collSelect = Data.collSelect.filter((itemc) => {
    return itemc !== ''
  })
  if (collSelect.length === 0) {
    Data.dataForm.forEach((item) => {
      item.isShow = true
    })
    return
  }
  Data.dataForm.forEach((item) => {
    const list = Data.collSelect.filter((x, index) => {
      if (x === '') {
        return ''
      }
      return item.name.indexOf(x) > -1 && item.name[index] === x
    })
    // const list = [...new Set(collSelect)].filter(x => s.has(x))
    if (list.length > 0 && list.length === collSelect.length) {
      item.isShow = true
    } else {
      item.isShow = false
    }
  })
}

// 选中规格值
const changeCollapse = (val, isShow) => {
  if (isShow) {
    Data.specTeamSel = val
    Data.isMask = true
  } else {
    Data.specTeamSel = -1
    Data.isMask = false
  }
}

// 关闭下拉
const closeVal = () => {
  Data.specTeamSel = -1
  Data.isMask = false
}
</script>

<style lang="scss" scoped>
@use "specification-breakdown";
</style>
